/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2020-1-1
 */

// 工具类
import util from './utils/util.js';
const func = require('./utils/func.js');

import config from './config.js';
import setting from './setting.js';


App({

	/**
	 * 全局变量
	 */
	globalData: {
		timer: 0,
		users_id: null,
		config: config,
		setting:setting,
		tabbar: setting.tabbar, // 底部导航菜单
	},

	/**
	 * 生命周期函数--监听小程序初始化
	 */
	onLaunch(e) {
		let _this = this;
		// 小程序主动更新
		_this.updateManager();
		// 小程序启动场景
		_this.onStartupScene(e.query);
	},
	
	// 验证业务域名授权状态
	checkAuthorization: function (that) {
		let _this = this;

		// let pages = getCurrentPages()
		// let currentPage = pages[pages.length - 1]
		// let path = currentPage.route
		// let is_check = false; // 默认不需要请求验证
		// let path_arr = path.split('/');
		// let array = ['category', 'index', 'article', 'contact', 'custom', 'guestbook', 'search'];
		// for (var i in array) {
		//   if (array[i] == path_arr[1]) {
		//     is_check = true;
		//     break;
		//   }
		// }
		// if (is_check != true) {
		//   return true;
		// }

		wx.request({
			url: _this.globalData.config.apiServerUrl,
			data: {},
			header: {
				'content-type': 'application/json' // 默认值
			},
			success: function (res) {
				that.setData({
					webconfig: res.data.webconfig
				})

				wx.setStorageSync('webconfig', res.data.webconfig)
				if (res.data.webconfig.authorization == -1) {
					var authorizationTitle = _this.globalData.config.authorizationTitle
					if (res.data.webconfig.authorizationTitle) {
						authorizationTitle = res.data.webconfig.authorizationTitle
					}
					var authorizationMsg = _this.globalData.config.authorizationMsg
					if (res.data.webconfig.authorizationMsg) {
						authorizationMsg = res.data.webconfig.authorizationMsg
					}
					wx.showModal({
						title: authorizationTitle,
						content: authorizationMsg,
						showCancel: false,
						confirmText: '知道了',
						success(res) {
							if (res.confirm) {
								wx.reLaunch({
									url: '/pages/index/index',
								})
							}
						}
					})
				}
			}
		})
	},

	/**
	 * 小程序启动场景
	 */
	onStartupScene(query) {

	},

	/**
	 * 获取小程序appid
	 */
	getAppId() {
		return config.appId;
	},

	/**
	 * 当小程序启动，或从后台进入前台显示，会触发 onShow
	 */
	onShow(options) {

	},

	/**
	 * 执行用户登录
	 */
	doLogin(delta) {
		// 保存当前页面
		let pages = getCurrentPages();
		if (pages.length) {
			let currentPage = pages[pages.length - 1];
			"pages/login/login" != currentPage.route &&
				wx.setStorageSync("currentPage", currentPage);
		}
		// 跳转授权页面
		wx.navigateTo({
			url: "/pages/login/login?delta=" + (delta || 1)
		});
	},

	/**
	 * 当前用户id
	 */
	getUserId() {
		return wx.getStorageSync('users_id');
	},

	/**
	 * 显示成功提示框
	 */
	showSuccess(msg, callback) {
		wx.showToast({
			title: msg,
			icon: 'success',
			mask: true,
			duration: 1500,
			success() {
				callback && (setTimeout(function () {
					callback();
				}, 1500));
			}
		});
	},

	/**
	 * 显示失败提示框
	 */
	showError(msg, callback) {
		wx.showModal({
			title: '友情提示',
			content: msg,
			showCancel: false,
			success(res) {
				// callback && (setTimeout(function() {
				//   callback();
				// }, 1500));
				callback && callback();
			}
		});
	},

	// api标签接口数据
	_requestApi: function (that, url, data, success, fail, complete) {
		let _this = this;
		wx.showLoading({
			title: '加载中',
			mask: true,
			fail: function () {
				wx.hideLoading();
			}
		});

		// 构造请求参数
		data = data || {};
		data.appId = _this.getAppId();
		data.token = wx.getStorageSync('token');
		data._ajax = 1;

		let request = function () {
			wx.request({
				url: url,
				header: {
					'content-type': 'application/json'
				},
				method: 'POST',
				data: data,
				success(res) {
					if (res.statusCode !== 200 || typeof res.data !== 'object') {
						_this.showError(res.data);
						return false;
					}
					if (res.data.code == 1) {
						if(res.data.data.cart_total_num){
							wx.setTabBarBadge({
								index: setting.cart_index,
								text: String(res.data.data.cart_total_num)
							})
						}else{
							wx.removeTabBarBadge({
								index: setting.cart_index
							})
						}
						success && success(res.data);
						that.setData({
							isApiLoaded: true // api请求加载完成
						});
					} else {
						_this.showError(res.data.msg);
					}
				},
				fail(res) {
					_this.showError(res.errMsg, function () {
						fail && fail(res);
					});
				},
				complete(res) {
					wx.hideLoading();
					complete && complete(res);
				},
			});
		};
		// 执行接口请求
		request();
	},

	// get请求api
	_requestGet: function (that, url, data, success, fail, complete, showLoadTitle, isShowNavBarLoading, check_login) {
		let _this = this;

		// 在当前页面显示导航条加载动画
		isShowNavBarLoading || true;
		isShowNavBarLoading && wx.showNavigationBarLoading();

		// 构造请求参数
		data = data || {};
		data.appId = _this.getAppId();
		data.token = wx.getStorageSync('token');

		let request = function () {
			wx.request({
				url: url,
				header: {
					'content-type': 'application/json'
				},
				method: 'GET',
				data: data,
				success(res) {
					if (res.statusCode !== 200 || typeof res.data !== 'object') {
						_this.showError('未知错误，无法继续~');
						return false;
					}
					if (res.data.data.code === -1) {
						// 登录态失效, 重新登录
						isShowNavBarLoading && wx.hideNavigationBarLoading();
						_this.doLogin(2);
					} else if (res.data.code === 0) {
						_this.showError(res.data.msg, function () {
							let firstchat = res.data.url.substr(0, 1);
							if (firstchat != '/') res.data.url = '/' + res.data.url;
							let pageschat = res.data.url.substr(0, 7);
							if (res.data.url.length > 0 && pageschat == '/pages/') {
								wx.navigateTo({
									url: res.data.url
								});
							} else {
								fail && fail(res);
							}
						});
						return false;
					} else {
						if(res.data.data.cart_total_num){
							wx.setTabBarBadge({
								index: setting.cart_index,
								text: String(res.data.data.cart_total_num)
							})
						}else{
							wx.removeTabBarBadge({
								index: setting.cart_index
							})
						}
						success && success(res.data);
					}
				},
				fail(res) {
					_this.showError(res.errMsg, function () {
						fail && fail(res);
					});
				},
				complete(res) {
					showLoadTitle !== false && wx.hideLoading();
					wx.hideNavigationBarLoading();
					complete && complete(res);
				},
			});
		};

		if (showLoadTitle === false) {
			// 判断是否需要验证登录
			check_login ? _this.doLogin(request) : request();
		} else {
			wx.showLoading({
				title: showLoadTitle || '加载中',
				mask: true,
				success: function () {
					// 判断是否需要验证登录
					check_login ? _this.doLogin(request) : request();
				},
				fail: function () {
					wx.hideLoading();
				}
			});
		}
	},

	/**
	 * post提交
	 */
	_requestPost: function (that, url, data, success, fail, complete, showLoadTitle, isShowNavBarLoading) {
		let _this = this;

		// 在当前页面显示导航条加载动画
		isShowNavBarLoading || true;
		isShowNavBarLoading && wx.showNavigationBarLoading();

		// 构造请求参数
		data = data || {};
		data.appId = _this.getAppId();
		data.token = wx.getStorageSync('token');
		
		let request = function () {
			wx.request({
				url: url,
				header: {
					'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
				},
				method: 'POST',
				data: data,
				success(res) {
					showLoadTitle !== false && wx.hideLoading();

					if (res.statusCode !== 200 || typeof res.data !== 'object') {
						_this.showError('未知错误，无法继续~');
						return false;
					}
					if (res.data.data.code === -1) {
						// 登录态失效, 重新登录
						isShowNavBarLoading && wx.hideNavigationBarLoading();
						_this.doLogin(1);
					} else if (res.data.code === 0) {
						_this.showError(res.data.msg, function () {
							fail && fail(res);
						});
						return false;
					} else {
						if(res.data.data.cart_total_num){
							wx.setTabBarBadge({
								index: setting.cart_index,
								text: String(res.data.data.cart_total_num)
							})
						}else{
							wx.removeTabBarBadge({
								index: setting.cart_index
							})
						}
						success && success(res.data);
					}
				},
				fail(res) {
					showLoadTitle !== false && wx.hideLoading();

					_this.showError(res.errMsg, function () {
						fail && fail(res);
					});
				},
				complete(res) {
					isShowNavBarLoading && wx.hideNavigationBarLoading();
					complete && complete(res);
				},
			});
		};
		if (showLoadTitle === false) {
			request();
		} else {
			wx.showLoading({
				title: showLoadTitle || '处理中',
				mask: true,
				success: function () {
					request();
				},
				fail: function () {
					wx.hideLoading();
				}
			});
		}
	},

	/**
	 * 验证是否存在user_info
	 */
	validateUserInfo() {
		// let user_info = wx.getStorageSync('user_info');
		return !!wx.getStorageSync('user_info');
	},

	/**
	 * 小程序主动更新
	 */
	updateManager() {
		if (!wx.canIUse('getUpdateManager')) {
			return false;
		}
		const updateManager = wx.getUpdateManager();
		updateManager.onCheckForUpdate(function (res) {
			// 请求完新版本信息的回调
		});
		updateManager.onUpdateReady(function () {
			wx.showModal({
				title: '更新提示',
				content: '新版本已经准备好，即将重启应用',
				showCancel: false,
				success(res) {
					if (res.confirm) {
						// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
						updateManager.applyUpdate();
					}
				}
			});
		});
		updateManager.onUpdateFailed(function () {
			// 新的版本下载失败
			wx.showModal({
				title: '更新提示',
				content: '新版本下载失败！',
				showCancel: false
			});
		});
	},

	/**
	 * 跳转到指定页面
	 * 支持tabBar页面
	 */
	navigationTo(url) {
		if (!url || url.length == 0) {
			return false;
		}
		func.switchTab(url, 'navigateTo');
	},

	/**
	 * 记录formId
	 */
	saveFormId(formId) {
		let _this = this;
		if (formId === 'the formId is a mock one') {
			return false;
		}
	},

	/**
	 * 生成转发的url参数
	 */
	getShareUrlParams(params) {
		let _this = this;
		return util.urlEncode(Object.assign({
			referee_id: _this.getUserId()
		}, params));
	},

	/**
	 * 余额充值支付
	 */
	balancePayment(option) {
		let options = Object.assign({
			payment: {},
			success: () => {},
			fail: () => {},
			complete: () => {},
		}, option);
		wx.requestPayment({
			timeStamp: options.payment.timeStamp,
			nonceStr: options.payment.nonceStr,
			package: 'prepay_id=' + options.payment.prepay_id,
			signType: 'MD5',
			paySign: options.payment.paySign,
			success(res) {
				options.success(res);
			},
			fail(res) {
				options.fail(res);
			},
			complete(res) {
				options.complete(res);
			}
		});
	},

	/**
	 * 订单支付 - 发起微信支付
	 */
	wxPayment(option) {
		let options = Object.assign({
			payment: {},
			success: () => {},
			fail: () => {},
			complete: () => {},
		}, option);
		wx.requestPayment({
			timeStamp: options.payment.timeStamp,
			nonceStr: options.payment.nonceStr,
			package: 'prepay_id=' + options.payment.prepay_id,
			signType: 'MD5',
			paySign: options.payment.paySign,
			success(res) {
				options.success(res);
			},
			fail(res) {
				options.fail(res);
				wx.redirectTo({
					url: '/pages/order/detail?order_id='+options.order_id,
				})
			},
			complete(res) {
				options.complete(res);
				wx.redirectTo({
					url: '/pages/order/detail?order_id='+options.order_id,
				})
			}
		});
	},

	/**
	 * 验证登录
	 */
	checkIsLogin() {
		return wx.getStorageSync('token') != '' && wx.getStorageSync('users_id') != '';
	},

	/**
	 * 授权登录
	 */
	getUserProfile(obj, callback) {
		let _this = this;
		wx.getUserProfile({
			desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: (e) => {
				let App = this;
				if (e.errMsg !== 'getUserProfile:ok') {
					return false;
				}
				wx.showLoading({
					title: "正在登录",
					mask: true
				});
				// 执行微信登录
				wx.login({
					success(res) {
						// 发送用户信息
						App._requestPost(_this, App.globalData.config.apiUsersloginUrl, {
							code: res.code,
							user_info: e.rawData,
							encrypted_data: e.encryptedData,
							iv: e.iv,
							signature: e.signature,
							// referee_id: wx.getStorageSync('referee_id')
						}, result => {
							// 记录token users_id
							wx.setStorageSync('token', result.data.token);
							wx.setStorageSync('users_id', result.data.users_id);
							// 执行回调函数
							callback && callback();
						}, false, () => {
							wx.hideLoading();
						});
					}
				});
			}
		})
	},
});